package cn.hackcloud.concurrency.eda;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 路由分发
 * Created by www.hackcloud.cn
 */
public final class EventDispatcher implements DynamicRouter<Message> {
    //用于保存Channel和Message之间的关系
    private final Map<Class<? extends Message>, Channel> routerTable;

    public EventDispatcher() {
        //初始化路由表
        this.routerTable = new ConcurrentHashMap<>();
    }

    @Override
    public void registerChannel(Class<? extends Message> messageType, Channel<? extends Message> channel) {
        this.routerTable.put(messageType, channel);
    }

    @Override
    public void dispatch(Message message) {
        if (routerTable.containsKey(message.getType())) {
            //直接获取对应的Channel处理Message
            routerTable.get(message.getType()).dispatch(message);
        } else {
            throw new MessageMatchException("can't match the channel for [" + message.getType() + "] type.");
        }
    }
}
